import React, { PureComponent } from "react";
import {
  Text,
  View,
  Image,
  TextInput,
  Alert,
  Platform,
  TouchableOpacity,
  Keyboard,
  StyleSheet
} from "react-native";
import {
  statusBarHeight,
  safeAreaBottomHeight,
  LoginToken,
  screenHeight
} from "../../util/AdapterUtil";
import NavigationService from "../../components/NavigationService";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import actions from "../../models/actions";
import { connect } from "react-redux";
import NavigationBar from "../../components/navigationBar";
import * as requestApi from "../../util/requestApi";
import MD5 from "react-native-md5";

class SubAccountScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      phone1: "",
      phone2: "",
      phone3: "",
      password1: "",
      password2: "",
      password3: "",
      userId1: "",
      userId2: "",
      userId3: ""
    };
  }
  componentWillUnmount() {}
  componentDidMount() {
    this.getSubAccount();
  }

  render() {
    return (
      <View style={{ flex: 1, backgroundColor: "#fff" }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={"子账号"}
        />
        <KeyboardAwareScrollView>
          <TouchableOpacity
            onPress={this.hiddenKeyborad.bind(this)}
            activeOpacity={1}
            style={{
              height:
                screenHeight - safeAreaBottomHeight - statusBarHeight - 44 - 10
            }}
          >
            <View style={{ height: 8, backgroundColor: "#F9F9F9" }} />

            <View>
              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>子账号1:</Text>
              </View>

              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>手机号码</Text>

                <TextInput
                  style={[
                    styles.itemStyle,
                    {
                      padding: 0,
                      textAlign: "right",
                      color: "#606060",
                      fontSize: 16,
                      flex: 1,
                      alignItems: "center",
                      justifyContent: "center"
                    }
                  ]}
                  placeholder={"请输入手机号码"}
                  keyboardType={"numeric"}
                  maxLength={11}
                  value={this.state.phone1}
                  onChangeText={text => {
                    const newText = text.replace(/[^\d]+/, "");
                    this.setState({
                      phone1: newText
                    });
                  }}
                />
              </View>

              <View
                style={{
                  marginLeft: 20,
                  height: 1,
                  backgroundColor: "#ccc",
                  transform: [{ scaleY: 0.5 }]
                }}
              />

              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>登录密码</Text>

                <TextInput
                  style={[
                    styles.itemStyle,
                    {
                      padding: 0,
                      textAlign: "right",
                      color: "#606060",
                      fontSize: 16,
                      flex: 1,
                      alignItems: "center",
                      justifyContent: "center"
                    }
                  ]}
                  placeholder={"请输入登录密码"}
                  secureTextEntry={true}
                  maxLength={16}
                  value={this.state.password1}
                  onChangeText={text => {
                    if (this.isPassword(text)) {
                      Toast.show("密码只能输入字母或数字", 1000);
                    }
                    let newtext = text.replace(/[^\da-zA-Z]+/, "");
                    if (text != null && text.length >= 18) {
                      Toast.show("密码最多16个字符", 1000);
                    } else {
                      this.setState({
                        password1: newtext
                      });
                    }
                  }}
                />
              </View>
            </View>

            <View>
              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>子账号2:</Text>
              </View>

              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>手机号码</Text>

                <TextInput
                  style={[
                    styles.itemStyle,
                    {
                      padding: 0,
                      textAlign: "right",
                      color: "#606060",
                      fontSize: 16,
                      flex: 1,
                      alignItems: "center",
                      justifyContent: "center"
                    }
                  ]}
                  placeholder={"请输入手机号码"}
                  keyboardType={"numeric"}
                  maxLength={11}
                  value={this.state.phone2}
                  onChangeText={text => {
                    const newText = text.replace(/[^\d]+/, "");
                    this.setState({
                      phone2: newText
                    });
                  }}
                />
              </View>

              <View
                style={{
                  marginLeft: 20,
                  height: 1,
                  backgroundColor: "#ccc",
                  transform: [{ scaleY: 0.5 }]
                }}
              />

              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>登录密码</Text>

                <TextInput
                  style={[
                    styles.itemStyle,
                    {
                      padding: 0,
                      textAlign: "right",
                      color: "#606060",
                      fontSize: 16,
                      flex: 1,
                      alignItems: "center",
                      justifyContent: "center"
                    }
                  ]}
                  placeholder={"请输入登录密码"}
                  secureTextEntry={true}
                  maxLength={16}
                  value={this.state.password2}
                  onChangeText={text => {
                    if (this.isPassword(text)) {
                      Toast.show("密码只能输入字母或数字", 1000);
                    }
                    let newtext = text.replace(/[^\da-zA-Z]+/, "");
                    if (text != null && text.length >= 18) {
                      Toast.show("密码最多16个字符", 1000);
                    } else {
                      this.setState({
                        password2: newtext
                      });
                    }
                  }}
                />
              </View>
            </View>

            <View>
              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>子账号3:</Text>
              </View>

              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>手机号码</Text>

                <TextInput
                  style={[
                    styles.itemStyle,
                    {
                      padding: 0,
                      textAlign: "right",
                      color: "#606060",
                      fontSize: 16,
                      flex: 1,
                      alignItems: "center",
                      justifyContent: "center"
                    }
                  ]}
                  placeholder={"请输入手机号码"}
                  keyboardType={"numeric"}
                  maxLength={11}
                  value={this.state.phone3}
                  onChangeText={text => {
                    const newText = text.replace(/[^\d]+/, "");
                    this.setState({
                      phone3: newText
                    });
                  }}
                />
              </View>

              <View
                style={{
                  marginLeft: 20,
                  height: 1,
                  backgroundColor: "#ccc",
                  transform: [{ scaleY: 0.5 }]
                }}
              />

              <View
                style={[
                  styles.itemStyle,
                  {
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }
                ]}
              >
                <Text style={{ color: "#606060", fontSize: 16 }}>登录密码</Text>

                <TextInput
                  style={[
                    styles.itemStyle,
                    {
                      padding: 0,
                      textAlign: "right",
                      color: "#606060",
                      fontSize: 16,
                      flex: 1,
                      alignItems: "center",
                      justifyContent: "center"
                    }
                  ]}
                  placeholder={"请输入登录密码"}
                  secureTextEntry={true}
                  maxLength={16}
                  value={this.state.password3}
                  onChangeText={text => {
                    if (this.isPassword(text)) {
                      Toast.show("密码只能输入字母或数字", 1000);
                    }
                    let newtext = text.replace(/[^\da-zA-Z]+/, "");
                    if (text != null && text.length >= 18) {
                      Toast.show("密码最多16个字符", 1000);
                    } else {
                      this.setState({
                        password3: newtext
                      });
                    }
                  }}
                />
              </View>
            </View>

            <TouchableOpacity
              style={{
                marginTop: 30,
                marginLeft: 20,
                marginRight: 20,
                height: 45,
                borderRadius: 6,
                backgroundColor: "#3591FF",
                justifyContent: "center",
                alignItems: "center"
              }}
              onPress={this.saveSubAccount.bind(this)}
            >
              <Text style={{ color: "#fff", fontSize: 14 }}>保存更新</Text>
            </TouchableOpacity>
          </TouchableOpacity>
        </KeyboardAwareScrollView>
        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  hiddenKeyborad() {
    Keyboard.dismiss();
  }

  isPassword = password => {
    const reg = /[^\da-zA-Z]+/;
    if (password == "●●●●●") {
      return false;
    } else {
      return reg.test(password);
    }
  };

  saveSubAccount() {
    let subUserParams = [];
    const isPhoneNumber = this.isPhoneNumber;
    let {
      phone1,
      phone2,
      phone3,
      password1,
      password2,
      password3,
      userId1,
      userId2,
      userId3
    } = this.state;
    if (
      (phone1 == null || phone1 == "") &&
      (phone2 == null || phone2 == "") &&
      (phone3 == null || phone3 == "")
    ) {
      return;
    }

    if (phone1 != null && phone1 !== "") {
      if (isPhoneNumber(phone1)) {
        Toast.show("子账号1，手机格式不对", 1000);
      }
      if (password1 == null || password1 == "") {
        Toast.show("密码不能为空", 1000);
        return;
      }
      if (password1.length < 8) {
        Toast.show("密码不能少于8位", 1000);
        return;
      }
      if (password1 == "●●●●●●") {
        subUserParams.push({ phone: phone1, password: "", userId: userId1 });
      } else {
        let sign1 = MD5.hex_md5(password1);
        subUserParams.push({ phone: phone1, password: sign1, userId: userId1 });
      }
    }
    if (phone2 != null && phone2 !== "") {
      if (isPhoneNumber(phone2)) {
        Toast.show("子账号2，手机格式不对", 1000);
      }
      if (password2 == null || password2 == "") {
        Toast.show("密码不能为空", 1000);
        return;
      }
      if (password2.length < 8) {
        Toast.show("密码不能少于8位", 1000);
        return;
      }
      if (password2 == "●●●●●●") {
        subUserParams.push({ phone: phone2, password: "", userId: userId2 });
      } else {
        let sign2 = MD5.hex_md5(password2);
        subUserParams.push({ phone: phone2, password: sign2, userId: userId2 });
      }
    }
    if (phone3 != null && phone3 !== "") {
      if (isPhoneNumber(phone3)) {
        Toast.show("子账号3，手机格式不对", 1000);
      }
      if (password3 == null || password3 == "") {
        Toast.show("密码不能为空", 1000);
        return;
      }
      if (password3.length < 8) {
        Toast.show("密码不能少于8位", 1000);
        return;
      }
      if (password3 == "●●●●●●") {
        subUserParams.push({ phone: phone3, password: "", userId: userId3 });
      } else {
        let sign3 = MD5.hex_md5(password3);
        subUserParams.push({ phone: phone3, password: sign3, userId: userId3 });
      }
    }

    let params = { subUserParams: subUserParams };
    requestApi
      .saveSubUserInfo(params)
      .then(res => {
        Toast.show("保存成功", 1000);
      })
      .catch(err => {
        Toast.show(err.msg, 1000);
      });
  }

  isPhoneNumber = phoneNumber => {
    const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    return reg.test(phoneNumber);
  };

  getSubAccount = () => {
    requestApi
      .getSubUserInfo()
      .then(res => {
        if (res && res.length > 0) {
          this.setState({
            phone1: res[0].phone,
            password1: "●●●●●●",
            userId1: res[0].userId
          });
          if (res.length > 1) {
            this.setState({
              phone2: res[1].phone,
              password2: "●●●●●●",
              userId2: res[1].userId
            });
          }
          if (res.length > 2) {
            this.setState({
              phone3: res[2].phone,
              password3: "●●●●●●",
              userId3: res[2].userId
            });
          }
        }
      })
      .catch(err => {
        Toast.show(err.msg, 1000);
      });
  };
}

const styles = StyleSheet.create({
  itemStyle: {
    height: 50
  }
});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {
    getLoginToken: actions.getLoginToken
  }
)(SubAccountScreen);
